package com.youkeda.music.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.youkeda.music.model.Artist;
import com.youkeda.music.model.Song;
import com.youkeda.music.service.SongCrawlerService;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SongCrawlerServiceImpl implements SongCrawlerService {
    private Map<String, Artist> artists;
    private void init(){
        artists = new HashMap<String, Artist>();
    }

    //根据歌单Id，抓取数据

    public void start(String artistId) {
         if (artistId==null || artistId.equals("")){
             return ;
         }
        //执行初始化
        init();
        // 取得整体数据对象
        Map returnMap = getArtistObj(artistId);
        // 构建填充了属性的 Artist 实例
        Artist artist = buildArtist(returnMap);

        artist.setSongList(buildSong(returnMap));

        artists.put(artistId,artist);

    }

    private Artist buildArtist(Map returnMap) {
        // 从 Map 对象中取得 歌单 数据。歌单也是一个子 Map 对象。
        Map artistData = (Map) returnMap.get("artist");
        Artist artist = new Artist();
        artist.setId(artistData.get("id").toString());
        if (artistData.get("picUrl") != null) {
            artist.setPicUrl(artistData.get("picUrl").toString());
        }
        artist.setBriefDesc(artistData.get("briefDesc").toString());
        artist.setImg1v1Url(artistData.get("img1v1Url").toString());
        artist.setName(artistData.get("name").toString());
        artist.setAlias((List) artistData.get("alias"));

        return artist;
    }
    private List<Song> buildSong(Map returnData) {

        List<Song> songs = new ArrayList<>();
        String string = returnData.get("hotSongs").toString();
        //String ————>>>>JSONArray
        JSONArray tableData = JSONArray.parseArray(string);
        // 从 Map 对象中取得一组 歌曲 数据

        //  答案的方法
       /* List songsData = (List) returnData.get("hotSongs");
        for (int i = 0; i < songsData.size(); i++) {
            Map songData = (Map) songsData.get(i);
            Song songObj = new Song();
            songObj.setId(songData.get("id").toString());
            songObj.setName(songData.get("name").toString());

            songs.add(songObj);
        }*/
        for (Object arrayList : tableData){
            Map songMap = (Map)arrayList;
            Song song = new Song();
            song.setName(songMap.get("name").toString());
            song.setId(songMap.get("id").toString());
           // System.out.println(song.getName());
            songs.add(song);
        }
        return songs;
    }

    //根据歌单Id查询歌曲

    public Artist getArtist(String artistId) {
        return artists.get(artistId);
    }

    //根据歌单Id个歌曲id查询歌曲

    public Song getSong(String songId, String artistId) {
        Artist  artist = artists.get(artistId);
        List<Song> songs = artist.getSongList();

        for (Song song:songs){
            if (song.getId().equals(songId)) {
                System.out.println(song.getId());
                return song;
            }
        }

        return null;
    }
    private Map getArtistObj(String artistid){
        // 构建歌单url
        String url="http://neteaseapi.youkeda.com:3000/artists?id="+artistid;

        String content = getPageContentSync(url);
        // 反序列化成 Map 对象
        Map returnMap = JSON.parseObject(content,Map.class);

      return returnMap;
    }


    //爬取歌单信息
    OkHttpClient okHttpClient = new OkHttpClient();
    private String getPageContentSync(String url){

        if (StringUtils.isBlank(url)){
            return null;
        }



        Request request = new Request.Builder().url(url).build();

        Call call = okHttpClient.newCall(request);
        String result = null;
        try {
            result = call.execute().body().string();
            //System.out.println("call "+url+" centent's size is "+result.length());
           // System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("call "+ url +" error");
        }
        return result;
    }
}
